//
//  WNBaseWebVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import WebKit

private var webViewKVOContext = "webViewKVOContext"

class WNBaseWebVC: WNBaseVC, WKNavigationDelegate {

    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress", context: &webViewKVOContext)
    }
    
    lazy var progressView: UIProgressView = {
        let progress = UIProgressView()
        progress.frame = CGRect(x: 0, y: NaviTotalHeight, width: ScreenW, height: 1)
        progress.progressTintColor = .init(named: "blue_2090FB")
        progress.trackTintColor = .clear
        return progress
    }()
    
    lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration()
        config.suppressesIncrementalRendering = false
        config.allowsInlineMediaPlayback = true
        let webView = WKWebView(frame: CGRect.zero, configuration: config)
        webView.navigationDelegate = self
        webView.backgroundColor = .white
        webView.scrollView.backgroundColor = .white
        webView.isHidden = true
        return webView
    }()
    
    var urlStr = String()
    
    var titleStr: String?
    
    var showTitle: Bool = true

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewConfig() {
        view.addSubview(webView)
        view.insertSubview(progressView, aboveSubview: webView)
        if urlStr.count != 0 {
            urlStr = urlStr.trimmingCharacters(in: .whitespacesAndNewlines)
            if urlStr.hasPrefix("http") {
                webView.load(URLRequest.init(url: URL.init(string: urlStr)!))
                webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: &webViewKVOContext)
            }
        }
        navView.titleName = titleStr
        webView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(NaviTotalHeight)
            make.bottom.equalTo(-TabBarMargin)
        }
    }
    
    override func dataConfig() {
        pageName = titleStr ?? ""
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" && object as? WKWebView == webView && context == &webViewKVOContext {
            if let new = change?[NSKeyValueChangeKey.newKey] as? Double {
                if new > 0 && new < 1 {
                    progressView.progress = Float(webView.estimatedProgress)
                    progressView.isHidden = false
                }else if new == 1 {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.progressView.progress = Float(self.webView.estimatedProgress)
                    }) { (finished) in
                        self.progressView.isHidden = true
                    }
                }else {
                    progressView.setProgress(0, animated: false)
                    progressView.isHidden = true
                }
            }
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.readyState") { (obj, complete) in
            if obj as? String == "complete" && !self.webView.isLoading {
                self.webView.isHidden = false
            }
        }
    }
}
